﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Text;

namespace ZYB.Security
{
    internal class DESTools
    {
        /// <summary>
        /// 秘钥
        /// </summary>
        public const string Key = "AD67EA2F3BE6E5AD";
        private static readonly int[] CharArray=new int[100];
       

        static DESTools()
        {
            for (var i = 0; i < 10; i++)
            {
                CharArray[(byte) i] = i;
            }
            for (var i = 'A'; i < 'F'; i++)
            {
                CharArray[(byte) i] = (byte) i - 55;
            }

        }

        public static byte[] Encrypt(byte[] b)
        {
            using (var des = new DESCryptoServiceProvider())
            {
                des.Mode=CipherMode.ECB;
                des.Key = GetKeyByte();
                des.IV = GetKeyByte();
                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(b,0,b.Length);
                        cs.FlushFinalBlock();
                    }
                    return ms.ToArray();
                }
            }
        }

        public static byte[] Decrypt(byte[] b)
        {
            using (var des = new DESCryptoServiceProvider())
            {
                des.Mode = CipherMode.ECB;
                des.Key = GetKeyByte();
                des.IV = GetKeyByte();
                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(b, 0, b.Length);
                        cs.FlushFinalBlock();
                    }
                    return ms.ToArray();
                }
            }
        }


        private static byte[] GetKeyByte()
        {
            var r = new byte[8];
            var arr = Key.ToCharArray();
            for (var i = 0; i < 8; i++)
            {
                var itg = 16 * CharArray[arr[2 * i]] + CharArray[arr[2 * i + 1]];
                r[i] = (byte)itg;
            }
            
            return r;
        }
       
    }
}
